<template>
    <div class="user-container">
        <div class="header">
            <div class="query">
                <el-form
                    ref="queryForm"
                    :inline="true"
                    :model="queryForm"
                    class="demo-form-inline"
                    size="small"
                >
                    <el-form-item prop="username">
                        <el-input
                            placeholder="用户名"
                            v-model="queryForm.username"
                        ></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="query"
                            >查询</el-button
                        >
                    </el-form-item>
                </el-form>
            </div>
            <div class="operation">
                <el-button type="primary" size="small" @click="Add"
                    >新建</el-button
                >
                <el-button type="success" size="small" @click="Refresh"
                    >刷新</el-button
                >
                <el-button type="primary" size="small" @click="Edit"
                    >编辑</el-button
                >
                <el-button type="danger" size="small" @click="Delete"
                    >删除</el-button
                >
            </div>
        </div>
        <div class="data">
            <el-table
                ref="table"
                v-loading="listLoading"
                :data="list"
                element-loading-text="Loading"
                border
                @row-click="handleRowClick"
                fit
                highlight-current-row
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center">
                </el-table-column>
                <el-table-column align="center" label="序号" width="95">
                    <template slot-scope="scope">
                        {{ scope.$index }}
                    </template>
                </el-table-column>
                <el-table-column label="昵称" prop="nickname" width="200">
                </el-table-column>
                <el-table-column label="用户名" prop="username" width="140">
                </el-table-column>
                <el-table-column label="邮箱" align="center" prop="email">
                </el-table-column>
                <el-table-column label="头像" align="center" width="80">
                    <template slot-scope="scope">
                        <el-avatar
                            size="medium"
                            :src="scope.row.avatar"
                        ></el-avatar>
                    </template>
                </el-table-column>
                <el-table-column
                    label="地址"
                    prop="address"
                    width="200"
                ></el-table-column>
                <el-table-column label="手机号" prop="phone"></el-table-column>
                <el-table-column label="QQ" prop="qq" width="140">
                </el-table-column>
                <el-table-column label="状态" width="110" align="center">
                    <template slot-scope="scope">
                        <el-tag
                            :type="
                                scope.row.status == '1' ? 'primary' : 'danger'
                            "
                            >{{
                                scope.row.status
                                    | statusFilter(scope.row.status)
                            }}</el-tag
                        >
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150" align="center">
                    <template slot-scope="scope">
                        <el-button
                            type="primary"
                            icon="el-icon-setting"
                            @click.stop="showDialog(scope.row)"
                            >分配角色</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                :page-size="limit"
                class="pagination"
                background
                layout="prev, pager, next"
                :total="total"
                @current-change="handlePageChange"
            >
            </el-pagination>
        </div>

        <el-dialog title="分配权限" :visible.sync="roleDialog" width="50%">
            <div style="padding: 0 15px">
                <el-alert
                    type="info"
                    :closable="false"
                    style="margin-bottom: 15px"
                    >无法看到`status`为 【2】 的角色</el-alert
                >
                <el-form
                    :model="userRole"
                    ref="roleForm"
                    label-width="70px"
                    label-position="top"
                >
                    <el-form-item label="姓名">
                        <el-input disabled v-model="userRole.user"></el-input>
                    </el-form-item>
                    <el-form-item label="角色">
                        <el-select
                            style="width: 100%"
                            v-model="userRole.role"
                            multiple
                            placeholder="请选择"
                        >
                            <el-option
                                v-for="item in roles"
                                :key="item.id"
                                :label="item.description"
                                :value="item.id"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>

            <span slot="footer" class="dialog-footer">
                <el-button @click="roleDialog = false">取 消</el-button>
                <el-button type="primary" @click="saveUserRole"
                    >确 定</el-button
                >
            </span>
        </el-dialog>

        <el-dialog
            :title="mode == 'edit' ? '编辑' : '新建'"
            :visible.sync="dialogVisible"
            :close-on-click-modal="false"
            width="50%"
        >
            <el-form ref="form" size="small" :model="form" label-width="80px">
                <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="form.nickname"></el-input>
                </el-form-item>
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="form.username"></el-input>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-switch
                        v-model="form.status"
                        :active-value="1"
                        :inactive-value="0"
                    >
                    </el-switch>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="form.sex">
                        <el-radio label="1">男</el-radio>
                        <el-radio label="2">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email"></el-input>
                </el-form-item>
                <el-form-item label="生日" prop="birthday">
                    <el-date-picker
                        v-model="form.birthday"
                        type="date"
                        placeholder="选择日期"
                    >
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="地址" prop="address">
                    <el-input v-model="form.address"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="form.phone"></el-input>
                </el-form-item>
                <el-form-item label="QQ" prop="qq">
                    <el-input v-model="form.qq"></el-input>
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input v-model="form.description"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { pageSize } from "@/settings";
import _ from "lodash";
import {
    getList,
    add,
    deleteRow,
    update,
    getUserRole,
    saveUserRole,
} from "@/api/user";
import { getRoles } from "@/api/role";

export default {
    name: "User",
    data() {
        return {
            list: [],
            listLoading: true,
            total: 0,
            start: 0,
            limit: pageSize,
            // 新建用户弹窗
            dialogVisible: false,
            // 查询表单
            queryForm: {
                username: "",
            },
            roleDialog: false, // 分配权限弹窗
            selectData: [], // 选中行数据
            form: {
                nickname: "",
                username: "",
                sex: "1",
                email: "",
                address: "",
                status: 1,
                birthday: "",
                phone: "",
                qq: "",
                description: "",
            },
            mode: "new", // edit或者new
            roles: [], // 权限列表
            userRole: {
                user: "",
                role: "",
                userId: "",
            },
        };
    },
    created() {
        this.fetchData();
        this.fetchRoles();
    },
    methods: {
        Add() {
            this.dialogVisible = true;
            this.mode = "new";
            this.$nextTick(() => {
                this.$refs.form.resetFields();
            });
        },
        Refresh() {
            this.$refs.queryForm.resetFields();
            this.fetchData();
        },
        Edit() {
            if (this.selectData.length == 0) {
                return this.$message.error("未选择任何数据");
            }
            if (this.selectData.length !== 1) {
                return this.$message.error("只能操作一条数据");
            }
            this.mode = "edit";
            this.form = _.cloneDeep(this.selectData[0]);
            this.dialogVisible = true;
        },
        async Delete() {
            if (this.selectData.length == 0) {
                return this.$message.error("未选择任何数据");
            }
            const ids = this.selectData.map((item) => item.id).join(",");
            this.$confirm("是否删除选择的数据", "删除提醒", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(async () => {
                    const result = await deleteRow({
                        ids: ids,
                    });
                    if (result && result.code == 200) {
                        this.$message.success("删除成功");
                        this.fetchData();
                    } else {
                        this.$message.erro("删除失败");
                    }
                })
                .catch(() => {});
        },
        async saveUserRole() {
            const { code, message } = await saveUserRole({
                userId: this.userRole.userId,
                roleIds: this.userRole.role.join(","),
            });
            if (code == 200) {
                this.$message.success(message);
                this.roleDialog = false;
            } else {
                this.$message.error(message);
            }
        },
        fetchRoles() {
            getRoles().then((res) => {
                this.roles = res.data;
            });
        },
        async showDialog(row) {
            this.userRole.user = row.nickname;
            this.userRole.userId = row.id;
            const res = await getUserRole({ id: row.id });
            this.userRole.role = res.data.map((item) => item.id);
            this.roleDialog = true;
        },
        saveRole() {},
        // 行点击选中当前行
        handleRowClick(row) {
            this.$refs.table.toggleRowSelection(row);
        },
        handleSelectionChange(selection) {
            this.selectData = selection;
        },
        handlePageChange(param) {
            this.start = (param - 1) * this.limit;
            this.fetchData();
        },
        // 获取数据
        fetchData() {
            this.listLoading = true;
            getList({
                start: this.start,
                limit: this.limit,
                ...this.queryForm,
            }).then((response) => {
                this.list = response.data.records;
                this.total = response.data.total;
                this.listLoading = false;
            });
        },
        // 查询
        query() {
            this.fetchData();
        },
        async submit() {
            let result;
            if (this.mode == "edit") {
                result = await update(this.form);
            } else {
                result = await add(this.form);
            }
            const { code } = result;
            if (code == 200) {
                this.$message.success("操作成功");
                this.fetchData();
            } else {
                this.$message.erro("操作失败");
            }
            this.dialogVisible = false;
        },
        edit(row) {
            this.mode = "edit";
            this.dialogVisible = true;
            this.form = _.cloneDeep(row);
        },
    },
};
</script>
<style lang="scss" scoped>
.user-container {
    padding: 15px;
    .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .operation {
            margin-bottom: 18px;
        }
    }
    .pagination {
        margin-top: 10px;
    }
}
</style>
